/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package portal.system;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Riso
 */
@WebServlet(name = "ImageServlet", urlPatterns = {"/displayImage"})
public class ImageServlet extends HttpServlet {

    String driver = portal.constants.Database.DATABASE_DRIVER;
    Connection con = null;
    String userName = portal.constants.Database.DATABASE_USER;
    String password = portal.constants.Database.DATABASE_PASSWORD;
    String URL = portal.constants.Database.DATABASE_URL;
    HttpSession session;
    String sql;
    InputStream in = null;
    OutputStream out = null;
    static int poradie = 0;

    @Override
    public void init() {
        try {
            super.init();
            Class.forName(driver);
            con = DriverManager.getConnection(URL, userName, password);
        } catch (Exception ex) {
        }
    }

    private void VypisObrazokInzeratu(HttpServletResponse response, HttpServletRequest request) {
        try {
            sql = "select * from obrazky_inzerat where id_inzeratu=" + request.getParameter("id") + " and"
                    + " id_obrazku = (select min(id_obrazku) from obrazky_inzerat where id_inzeratu=" + request.getParameter("id") + ")";


            ResultSet rs = null;
            Statement stmt = null;
            stmt = con.createStatement();
            rs = stmt.executeQuery(sql);
            
            Blob imageToReturn=null;
            
            if (!rs.next()) {
                rs = stmt.executeQuery("select * from obrazky_inzerat where id_obrazku = 4");
                rs.next();
                imageToReturn = rs.getBlob("obrazok");
                in = imageToReturn.getBinaryStream();
                response.setContentLength((int) imageToReturn.length());
            }else{
                imageToReturn = rs.getBlob("obrazok");
                in = imageToReturn.getBinaryStream();
                response.setContentLength((int) imageToReturn.length());
            }

            response.setContentType("image/png");
            out = response.getOutputStream();

            byte[] buf = new byte[1024];
            int count = 0;
            while ((count = in.read(buf)) >= 0) {
                out.write(buf, 0, count);
                System.out.println("pisem");

            }
            out.flush();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private void VypisObrazok(HttpServletResponse response, HttpServletRequest request) {
        try {
            sql = "select obrazok from obrazky_inzerat where id_obrazku=" + request.getParameter("obr");


            ResultSet rs = null;
            Statement stmt = null;
            stmt = con.createStatement();
            rs = stmt.executeQuery(sql);
            rs.next();
            Blob imageToReturn = rs.getBlob("obrazok");
            response.setContentType("image/png");

            response.setContentLength((int) imageToReturn.length());
            //System.out.println("Id kategorie: "+rs.getString("id_kategorie"));

            in = imageToReturn.getBinaryStream();
            out = response.getOutputStream();

            byte[] buf = new byte[1024];
            int count = 0;
            while ((count = in.read(buf)) >= 0) {
                out.write(buf, 0, count);

            }
            out.flush();
            rs.close();
            stmt.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

    private void VypisObrazokKategorie(HttpServletResponse response, HttpServletRequest request) {
        try {
            sql = "select obrazok_kategorie,id_kategorie from kategorie where id_kategorie=" + request.getParameter("kat");


            ResultSet rs = null;
            Statement stmt = null;
            stmt = con.createStatement();
            rs = stmt.executeQuery(sql);
            rs.next();
            Blob imageToReturn = rs.getBlob("obrazok_kategorie");
            response.setContentType("image/png");

            response.setContentLength((int) imageToReturn.length());
            //System.out.println("Id kategorie: "+rs.getString("id_kategorie"));

            in = imageToReturn.getBinaryStream();
            out = response.getOutputStream();

            byte[] buf = new byte[1024];
            int count = 0;
            while ((count = in.read(buf)) >= 0) {
                out.write(buf, 0, count);

            }
            out.flush();
            rs.close();
            stmt.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected synchronized void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        try {
            if (request.getParameter("id") != null) {
                VypisObrazokInzeratu(response, request);
            } else if (request.getParameter("kat") != null) {
                VypisObrazokKategorie(response, request);
            } else if (request.getParameter("pod") != null) {
                VypisObrazokPodKategorie(response, request);
            } else if (request.getParameter("obr") != null) {
                VypisObrazok(response, request);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (Exception e) {
                    System.err.println(e.toString());
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (Exception e) {
                    System.err.println(e.toString());
                }
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private void VypisObrazokPodKategorie(HttpServletResponse response, HttpServletRequest request) {
        try {
            sql = "select obrazok,id_podkategorie from podkategorie where id_podkategorie=" + request.getParameter("pod");


            ResultSet rs = null;
            Statement stmt = null;
            stmt = con.createStatement();
            rs = stmt.executeQuery(sql);
            rs.next();
            Blob imageToReturn = rs.getBlob("obrazok");
            response.setContentType("image/png");

            response.setContentLength((int) imageToReturn.length());

            in = imageToReturn.getBinaryStream();
            out = response.getOutputStream();

            byte[] buf = new byte[1024];
            int count = 0;
            while ((count = in.read(buf)) >= 0) {
                out.write(buf, 0, count);

            }
            out.flush();
            rs.close();
            stmt.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
